// 数据统计模块 - 根据详细设计文档3.5节实现
const express = require('express');
const router = express.Router();
const pool = require('../config/database');
const { authenticateToken, checkPermission } = require('../middleware/auth');

/**
 * 运营概览接口
 * GET /api/statistics/overview
 */
router.get('/overview', authenticateToken, checkPermission('admin'), async (req, res) => {
  const { startDate, endDate } = req.query;
  console.log('📊 获取运营数据概览');

  try {
    const startTime = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const endTime = endDate ? new Date(endDate) : new Date();

    // 验证时间范围
    if ((endTime - startTime) / (1000 * 60 * 60 * 24) > 365) {
      return res.status(400).json({
        success: false,
        errorCode: 4001,
        errorMessage: '统计时间范围不能超过1年'
      });
    }

    // 核心指标统计
    const [orderStats] = await pool.execute(
      `SELECT 
                COUNT(*) as totalOrders,
                SUM(final_fee) as totalTransaction,
                COUNT(DISTINCT order_user_id) as uniqueOrderUsers
             FROM orders 
             WHERE created_at >= ? AND created_at <= ?`,
      [startTime, endTime]
    );

    const [userStats] = await pool.execute(
      `SELECT COUNT(*) as activeUsers 
             FROM users 
             WHERE last_login_at >= ? AND last_login_at <= ?`,
      [startTime, endTime]
    );

    const [courierStats] = await pool.execute(
      `SELECT COUNT(*) as activeCouriers 
             FROM courier_users cu
             INNER JOIN users u ON cu.user_id = u.id
             WHERE cu.status = 'active' AND u.account_status = 'active'`
    );

    const [completionStats] = await pool.execute(
      `SELECT 
                COUNT(*) as completedOrders,
                AVG(TIMESTAMPDIFF(MINUTE, created_at, completed_at)) as avgCompletionTime
             FROM orders 
             WHERE status IN (4, 5) 
             AND created_at >= ? AND created_at <= ?`,
      [startTime, endTime]
    );

    const [ratingStats] = await pool.execute(
      `SELECT AVG(rating) as averageRating 
             FROM ratings 
             WHERE created_at >= ? AND created_at <= ?`,
      [startTime, endTime]
    );

    const totalOrders = orderStats[0]?.totalOrders || 0;
    const completedOrders = completionStats[0]?.completedOrders || 0;
    const completionRate = totalOrders > 0
      ? ((completedOrders / totalOrders) * 100).toFixed(2)
      : '0.00';

    res.json({
      success: true,
      data: {
        summary: {
          totalOrders: totalOrders,
          totalTransaction: parseFloat(orderStats[0]?.totalTransaction || 0).toFixed(2),
          activeUsers: userStats[0]?.activeUsers || 0,
          activeCouriers: courierStats[0]?.activeCouriers || 0,
          completionRate: parseFloat(completionRate),
          averageRating: parseFloat(ratingStats[0]?.averageRating || 5.0).toFixed(1)
        },
        timeRange: {
          startDate: startTime.toISOString().split('T')[0],
          endDate: endTime.toISOString().split('T')[0]
        }
      }
    });

  } catch (error) {
    console.error('❌ 获取运营概览失败:', error);
    res.status(500).json({
      success: false,
      errorCode: 5001,
      errorMessage: '获取运营数据失败: ' + error.message
    });
  }
});

/**
 * 订单统计接口
 * GET /api/statistics/orders
 */
router.get('/orders', authenticateToken, checkPermission('admin'), async (req, res) => {
  const { period = 'daily', metrics = 'all' } = req.query;
  console.log('📈 获取订单统计数据');

  try {
    let dateFormat = '';
    let groupBy = '';

    switch (period) {
      case 'daily':
        dateFormat = 'DATE(created_at)';
        groupBy = 'DATE(created_at)';
        break;
      case 'weekly':
        dateFormat = 'YEARWEEK(created_at)';
        groupBy = 'YEARWEEK(created_at)';
        break;
      case 'monthly':
        dateFormat = 'DATE_FORMAT(created_at, "%Y-%m")';
        groupBy = 'DATE_FORMAT(created_at, "%Y-%m")';
        break;
      default:
        dateFormat = 'DATE(created_at)';
        groupBy = 'DATE(created_at)';
    }

    const [trendData] = await pool.execute(
      `SELECT 
                ${dateFormat} as period,
                COUNT(*) as orderCount,
                SUM(final_fee) as revenue,
                COUNT(CASE WHEN status IN (4, 5) THEN 1 END) as completedCount
             FROM orders 
             WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
             GROUP BY ${groupBy}
             ORDER BY period DESC
             LIMIT 30`
    );

    res.json({
      success: true,
      data: {
        trends: trendData,
        period: period
      }
    });

  } catch (error) {
    console.error('❌ 获取订单统计失败:', error);
    res.status(500).json({
      success: false,
      errorCode: 5001,
      errorMessage: '获取订单统计失败: ' + error.message
    });
  }
});

/**
 * 用户分析接口
 * GET /api/statistics/users
 */
router.get('/users', authenticateToken, checkPermission('admin'), async (req, res) => {
  const { userType, timeRange = '30' } = req.query;
  console.log('👥 获取用户分析数据');

  try {
    const days = parseInt(timeRange) || 30;

    const [growthData] = await pool.execute(
      `SELECT 
                DATE(created_at) as date,
                COUNT(*) as newUsers
             FROM users 
             WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY)
             ${userType ? `AND role = ?` : ''}
             GROUP BY DATE(created_at)
             ORDER BY date DESC`,
      userType ? [days, userType] : [days]
    );

    const [activityData] = await pool.execute(
      `SELECT 
                COUNT(DISTINCT user_id) as activeUsers,
                COUNT(*) as totalLogins
             FROM login_logs 
             WHERE login_at >= DATE_SUB(NOW(), INTERVAL ? DAY)`,
      [days]
    );

    res.json({
      success: true,
      data: {
        growth: growthData,
        activity: activityData[0] || { activeUsers: 0, totalLogins: 0 }
      }
    });

  } catch (error) {
    console.error('❌ 获取用户分析失败:', error);
    res.status(500).json({
      success: false,
      errorCode: 5001,
      errorMessage: '获取用户分析失败: ' + error.message
    });
  }
});

/**
 * 收入报表接口
 * GET /api/statistics/revenue
 */
router.get('/revenue', authenticateToken, checkPermission('admin'), async (req, res) => {
  const { startDate, endDate } = req.query;
  console.log('💰 获取收入报表');

  try {
    const startTime = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const endTime = endDate ? new Date(endDate) : new Date();

    // 收入明细
    const [revenueDetails] = await pool.execute(
      `SELECT 
                DATE(created_at) as date,
                SUM(final_fee) as totalRevenue,
                SUM(suggested_fee) as suggestedRevenue,
                COUNT(*) as orderCount
             FROM orders 
             WHERE status IN (4, 5)
             AND created_at >= ? AND created_at <= ?
             GROUP BY DATE(created_at)
             ORDER BY date DESC`,
      [startTime, endTime]
    );

    // 平台抽佣统计
    const [commissionStats] = await pool.execute(
      `SELECT 
                SUM(final_fee * 0.1) as totalCommission,
                COUNT(*) as paidOrders
             FROM orders 
             WHERE status IN (4, 5)
             AND created_at >= ? AND created_at <= ?`,
      [startTime, endTime]
    );

    res.json({
      success: true,
      data: {
        revenueDetails: revenueDetails,
        commissionStats: {
          totalCommission: parseFloat(commissionStats[0]?.totalCommission || 0).toFixed(2),
          paidOrders: commissionStats[0]?.paidOrders || 0
        }
      }
    });

  } catch (error) {
    console.error('❌ 获取收入报表失败:', error);
    res.status(500).json({
      success: false,
      errorCode: 5001,
      errorMessage: '获取收入报表失败: ' + error.message
    });
  }
});

module.exports = router;

